Extend a Data Object
As the Data Objects are generated as partial classes, it is easy to extend them with some business logic:
using System; using System.Collections.Generic; using System.Text; using MyProject.BusinessLogic.BusinessObjects.Commands; namespace MyProject.BusinessLogic.BusinessObjects { public partial class Employee { } } |
Notice that the namespace is the same as in the generated class Employee (in the Generated folder). So now the Employee class is devided into two parts, the generated part and the part for individual code that you have created.
After that your current solution structure should look like this:
As next, include the following method into the Employee class:
/// <summary> /// Finds all Employee objects with a certain last name and first name. /// </summary> /// <param name="lastname">The last name ('*' can be used as a wildcard).</param> /// <param name="firstname">The first name ('*' can be used as a wildcard).</param> /// <returns>A list of Employee objects with a certain last name and first name.</returns> public static IList<Employee> FindByFullName(string lastname, string firstname) { return Employee.Query(EmployeeCommands.FindByFullName(lastname, firstname)); } |
Now, you have extended the Employee class with a new query method. Notice that all the data access code is encapsulated, the presentation layer has to use the method FindByFullName of the Employee business object. So the presentation layer is free of database-specific code.
As next, include the following methods into the Employee class:
private void prePersist() { string error;
if (!this.Validate(out error)) throw new Exception(error); } public bool Validate(out string validationError) { if (String.IsNullOrEmpty(this.Firstname)) { validationError = "The Firstname is empty"; return false; } if (String.IsNullOrEmpty(this.Lastname)) { validationError = "The Lastname is empty"; return false; } if (this.Birthdate > DateTime.Now) { validationError = "The birthday is in the future"; return false; } validationError = null; return true; } |
The first method prePersist is a special method that is excecuted as the first action of the Persist method.
The second method validates if the required fields are set and if the Birthday property has a valid date.
So with these two methods, it is not possible to persist an Employee with invalid data.
In the next section, the one-to-many association between the Employees and the Orders is implemented.